{% block as_form %}
    <select class="form-control select"
            id="{{ field.key }}"
            name="{{ field.key }}"
            data-choices
    >

                {% if field.val %}
                    <option value="{{ field.val.id }}" selected> {{ field.val.name }}</option>
                {% endif %}
    </select>
    <script>
        (async function () {
            let element = document.getElementById("{{ field.key }}");
            let choices = new Choices(element, {
                removeItemButton: true
            });
            {% if not field.is_filter %}
            function check_valid() {
                if (element.required) {
                    choices.containerInner.element.classList.add('is-invalid');
                    choices.containerInner.element.classList.remove('is-valid');
                } else {
                    choices.containerInner.element.classList.remove('is-invalid');
                    choices.containerInner.element.classList.add('is-valid');
                }
            }
             check_valid()
            {% endif %}
            function init(){
                choices.setChoices(async () => {
                    try {
                        const items = await fetch('/base/search?model={{ field.model_name }}&search=');
                        const results = await items.json();
                        if (0 === results.length) { // Handle error from result, for example.
                            throw 'Empty!';
                        }
                        return results;
                    } catch (err) {
                        console.error(err);
                    }
                }).then(() => {
                    choices.input.element.focus()
                });
            }
            init()

        })();
    </script>
{% endblock %}
{% block as_view %}
    <input  type="text"
                    class="form-control"
                    {% if field.required %} required {% endif %}
                    disabled
                    name="{{ field.key }}"
                    placeholder="Enter {{ field.title }}"
                    value="{{ field.val.english_name or field.val.name or field.val}}"
            >

{% endblock %}